# -*- coding: UTF-8 -*-
"""
@Project , trainee
@File    , word_cloud.py
@IDE     , PyCharm
@Author  , 2607750505@qq.com
@Date    , 2025/6/16 15:26
"""
import stylecloud
from tools.getDataBase import get_conn

from wordcloud import WordCloud
import os
from flask import current_app


# 实现标题词云
# 需要绘制的字段、图标名称、输出名称
# 实现标题词云
def getTitleImg(field, icon_name, output_name):
    sql = f'select {field} from movies'
    conn, cursor = get_conn()
    cursor.execute(sql)
    data = cursor.fetchall()
    text = ','.join([row[0] for row in data])
    font_path = os.path.join(current_app.root_path, 'static', 'fonts', 'simhei.ttf')
    wc = WordCloud(font_path=font_path, width=800, height=400, background_color='white')
    wc.generate(text)
    wc.to_file(output_name)

# 实现演员名词云
def getCastsImg(field, icon_name, output_name):
    sql = f'select {field} from movies'
    conn, cursor = get_conn()
    cursor.execute(sql)
    data = cursor.fetchall()
    text1 = ','.join([row[0] for row in data])
    font_path = os.path.join(current_app.root_path, 'static', 'fonts', 'simhei.ttf')
    wc = WordCloud(font_path=font_path, width=800, height=400, background_color='white')
    wc.generate(text1)
    wc.to_file(output_name)

# 实现自定义
def getCastsImg(field, icon_name, output_name):
    sql = f'select {field} from movies'
    conn, cursor = get_conn()
    cursor.execute(sql)
    data = cursor.fetchall()
    text1 = ','.join([row[0] for row in data])
    font_path = os.path.join(current_app.root_path, 'static', 'fonts', 'simhei.ttf')
    wc = WordCloud(font_path=font_path, width=800, height=400, background_color='white')
    wc.generate(text1)
    wc.to_file(output_name)

# def getCommentsImg(field, serchWord, icon_name, output_name):
#     sql = f'select {field} from comments where movieName="{serchWord}"'
#     conn, cursor = get_conn()
#     cursor.execute(sql)
#     data = cursor.fetchall()
#     text1 = ','.join([row[0] for row in data])
#     font_path = os.path.join(current_app.root_path, 'static', 'fonts', 'simhei.ttf')
#     wc = WordCloud(font_path=font_path, width=800, height=400, background_color='white')
#     wc.generate(text1)
#     wc.to_file(output_name)

def getCommentsImg(field, searchWord, icon_name, output_name):
    try:
        # 使用模糊查询避免名称不匹配问题
        sql = f"SELECT {field} FROM comments WHERE movieName LIKE %s"
        conn, cursor = get_conn()
        cursor.execute(sql, (f"%{searchWord}%",))
        data = cursor.fetchall()

        if not data:
            # 尝试获取相似电影名称，辅助用户修正
            similar_movies = []
            movie_sql = "SELECT DISTINCT movieName FROM comments WHERE movieName LIKE %s LIMIT 5"
            cursor.execute(movie_sql, (f"%{searchWord}%",))
            similar_movies = [row[0] for row in cursor.fetchall()]

            if similar_movies:
                hint = f"你可以尝试: {', '.join(similar_movies)}"
            else:
                hint = "请检查电影名称是否正确"

            raise ValueError(f"没有找到电影 '{searchWord}' 的评论数据。{hint}")

        # 处理评论数据
        text = ' '.join([str(row[0]) for row in data])

        # 动态获取字体
        font_path = os.path.join(current_app.root_path, 'static', 'fonts', 'simhei.ttf')

        # 检查字体文件是否存在
        if not os.path.exists(font_path):
            # 尝试使用系统字体
            try:
                import matplotlib.font_manager as fm
                chinese_fonts = [f for f in fm.findSystemFonts()
                                 if 'simhei' in f.lower() or 'heiti' in f.lower() or 'microsoftyahei' in f.lower()]
                if chinese_fonts:
                    font_path = chinese_fonts[0]
                else:
                    # 如果没有找到中文字体，使用默认字体（可能会导致中文显示异常）
                    font_path = None
                    print("警告: 未找到中文字体，中文可能无法正确显示")
            except:
                font_path = None
                print("警告: 字体检测失败，中文可能无法正确显示")

        # 生成词云
        wc = WordCloud(
            font_path=font_path,
            width=800,
            height=400,
            background_color='white',
            max_words=200,
            collocations=False
        )
        wc.generate(text)
        wc.to_file(output_name)
        return True

    except Exception as e:
        print(f"生成词云失败: {str(e)}")
        return False
